import { login, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { asyncRoutes, resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken() || '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token) // 持久化
  },
  removeToken(state) {
    state.token = ''
    removeToken() // 删除持久化
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}

const actions = {
  async login(context, data) {
    console.log(data)
    const token = await login(data)
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
    // 动态添加路由
    const route = asyncRoutes.filter(item => result.roles.menus.includes(item.name))
    router.addRoutes([...route, {
      path: '*',
      component: () => import('@/views/404'),
      hidden: true
    }])
    context.commit('route/setRoute', route, { root: true })
  },
  // 退出登录
  logout(context) {
    context.commit('removeToken')
    context.commit('setUserInfo', {})
    resetRouter() // 重新登录权限叠加问题
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

